package com.tramy.data.export.engine.impl;

import com.alibaba.fastjson.JSON;
import com.tramy.data.export.datasource.DatabaseContextHolder;
import com.tramy.data.export.datasource.DatabaseType;
import com.tramy.data.export.engine.DataEngine;
import com.tramy.data.export.mapper.EmployeeMapper;
import com.tramy.data.export.mapper.TramyEmployeeMapper;
import com.tramy.data.export.model.Employee;
import com.tramy.data.export.model.EmployeeExample;
import com.tramy.data.export.model.TramyEmployee;
import com.tramy.data.export.model.TramyEmployeeExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by honway on 2016/11/3.
 */
@Service
public class EmployeeDataEngine implements DataEngine {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TramyEmployeeMapper tramyEmployeeMapper;

    @Override
    public void justDoIt() {
        DatabaseContextHolder.setDatabaseType(DatabaseType.firehome);
        EmployeeExample example = new EmployeeExample();
        example.createCriteria().andEmployeeCodeIsNotNull();
        System.out.println("开始从新烽火中查询员工数据.");
        List<Employee> firehomeEmployees = employeeMapper.selectByExample(example);
        System.out.println("从新烽火中查询到:"+firehomeEmployees.size()+"条数据.");
        DatabaseContextHolder.setDatabaseType(DatabaseType.pinshang);
        System.out.println("开始将数据插入到新清美");
        List<TramyEmployee> convertResult = firehomeEmployees.parallelStream().map(Employee::convert).collect(Collectors.toList());
        proceedEmployee(convertResult);
    }

    /**
     * 处理新清美数据
     * @param convertResult 新清美员工数据
     */
    private long proceedEmployee(List<TramyEmployee> convertResult) {
        return convertResult.parallelStream().map(emp -> {
            TramyEmployeeExample example = new TramyEmployeeExample();
            String employeeCode = emp.getEmployeeCode();
            String employeeName = emp.getEmployeeName();
            if (StringUtils.isEmpty(employeeCode) || StringUtils.isEmpty(employeeName)) {
                System.out.println("发现一条非法数据:" + JSON.toJSONString(emp));
            } else {
                example.createCriteria().andEmployeeCodeEqualTo(employeeCode).andEmployeeNameEqualTo(employeeName);
                List<TramyEmployee> tramyEmployees = tramyEmployeeMapper.selectByExample(example);
                if (tramyEmployees == null || tramyEmployees.size() == 0) {
                    tramyEmployeeMapper.insertSelective(emp);
                }
            }
            return 1;
        }).count();
    }

}
